#!/usr/bin/python -u
# -*- coding: utf-8 -*-
from __future__ import absolute_import

# -- prioritized --
import sys
import os.path
sys.path.append(os.path.join(os.path.dirname(__file__), './libs'))
from gevent import monkey
monkey.patch_all()

# -- stdlib --
import json
import socket
import time
import signal
import urllib3

# -- third party --
from gevent.pool import Pool
import gevent
import requests

# -- own --
from utils.region import nodes_of

# -- code --
signal.signal(signal.SIGTERM, lambda num, frame: os._exit(0))

try:
    from requests.packages.urllib3.exceptions import InsecureRequestWarning
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
except ImportError:
    try:
        from urllib3.exceptions import InsecureRequestWarning
        urllib3.disable_warnings(InsecureRequestWarning)
    except ImportError:
        pass

endpoint = socket.gethostname()
ts = int(time.time())

args = json.loads(sys.stdin.read())
# [{'_metric': 'cross.agent', 'region': 'ops'}]
args, = args
assert args['_metric'] == 'cross.agent'

nodes = nodes_of(args['region'])


def detect(node):
    for i in xrange(3):
        try:
            resp = requests.get('http://%s:1988/v1/ping' % node, timeout=3).json()
            return (node, resp['result'] == 'pong')
        except Exception:
            continue

    return (node, False)


metric = [{
    "metric": "cross.agent.alive",
    "endpoint": node,
    "timestamp": ts,
    "step": args['_step'],
    "value": int(v),
    "tags": {"from": endpoint},
} for node, v, in Pool(60).imap_unordered(detect, nodes)]

print(json.dumps(metric))

gevent.sleep(0.01)  # Prevent threadpool crashes when script finishes too fast
